import axios from 'axios';

const getBaseUrl = 'http://www.bjdd301.cn:80/car/api1'
const postBaseUrl = 'http://www.bjdd301.cn:80/car/api2'
const postBaseUrl2 = 'http://www.bjdd301.cn:80/car/api3'

// const getBaseUrl = 'http://121.40.41.188:8080/car/api1'
// const postBaseUrl = 'http://121.40.41.188:8080/car/api2'
// const postBaseUrl2 = 'http://121.40.41.188:8080/car/api3'

const baseGet = (url, callback) => {
  axios.request({
    url: url,
    method: 'get'
  }).then(function (res) {
    callback(res)
  }).catch(function (error) {
    var result = {
      error: true
    }
    callback(result)
  })
}

export const evaluteCcw = (obj, _self, condition, callback) => {
  // var url = 'http://www.chechong.com/gujia/163761_2017_5_2_829_200_0_0_0/'
  var url = _self.$const.CCWURL + '/gujia/'
  url += condition.curModels.id + '_' + condition.selectedYear + '_' + condition.selectedMonth + '_2_' +
    condition.selectedCity.id + '_' + (parseInt(condition.distance) * 100) + '_0_0_0/'
  url = getBaseUrl + '?url=' + url
  baseGet(url, (res) => {
    var result = res
    if (!res.error) {
      result = getCcwEvaluteResult(obj, res.data.data, condition)
    }
    callback(result)
  })
}

const getCcwEvaluteResult = (obj, res, condition) => {
  res = res.replace(/\<script((.|\n)*?)\<\/script\>/gi, '')
  res = res.replace(/\<link((.|\n)*?)\/>/gi, '')
  res = res.replace(/\<head((.|\n)*?)\<\/head\>/gi, '')
  // res = res.replace(/<\s?img[^>]*>/gi, '')
  obj.html(res)
  // console.log(condition)
  let elements = obj.find('.pinggu_car')
  let result = {}
  // console.log(elements.find('dt > .img'))
  result.img = elements.find('dt > .img > img').attr('src')
  result.evalutePrice = elements.find('dd .car_ping #henhao').attr('lang')
  var allPrice = result.evalutePrice.split("-")
  result.maxPrice = allPrice[2]
  result.middlePrice = allPrice[1]
  result.minPrice = allPrice[0]
  result.newPrice = condition.curModels.new_price
  result.condition = condition
  result.error = false
  // console.log(result)
  obj.html('')
  return result
}

export const evaluteCth = (obj, _self, condition, callback) => {
  // var url = 'https://www.che300.com/pinggu/v1c1m32931r2016­1g2.33'
  // console.log(JSON.stringify(condition))
  var url = _self.$const.CTHURL + '/pinggu/'
  url += 'v' + condition.selectedProvince.id + 'c' + condition.selectedCity.id + 'm' + condition.curModels.model_id + 'r'
      + condition.selectedYear + '-' + condition.selectedMonth + 'g' + condition.distance
  // console.log(url)
  url = getBaseUrl + '?url=' + url
  baseGet(url, (res) => {
    var result = res
    if (!res.error) {
      result = analysisCthData(res.data.data, obj, condition)
    }
    callback(result)
  })
}

const analysisCthData = (res, obj, condition) => {
  var newRes = res
  newRes = newRes.replace(/\<script((.|\n)*?)\<\/script\>/gi, '')
  newRes = newRes.replace(/\<link((.|\n)*?)\/>/gi, '')
  newRes = newRes.replace(/\<head((.|\n)*?)\<\/head\>/gi, '')
  newRes = newRes.replace(/<script.*?>.*?<\/script>/ig, '')
  // newRes = newRes.replace(/<\s?img[^>]*>/gi, '')
  obj.html(newRes)
  var excellentClass = obj.find('#excellent .sp-price .sp-value .sp-strong span').attr('class')
  var goodClass = obj.find('#good .sp-price .sp-value .sp-strong span').attr('class')
  var commonClass = obj.find('#common .sp-price .sp-value .sp-strong span').attr('class')
  var img = obj.find('.result .result-wrap .rh img').attr('src')
  obj.html('')

  // 获取前面几位数
  var excellentStr = res.substring(res.indexOf('.' + excellentClass + ':before'), res.length)
  var excellentPreNum = (excellentStr.substring(0, excellentStr.indexOf('}')).split('content:\''))[1].split('\';')[0]

  var goodStr = res.substring(res.indexOf('.' + goodClass + ':before'), res.length)
  var goodPreNum = (goodStr.substring(0, goodStr.indexOf('}')).split('content:\''))[1].split('\';')[0]

  var commonStr = res.substring(res.indexOf('.' + commonClass + ':before'), res.length)
  var commonPreNum = (commonStr.substring(0, commonStr.indexOf('}')).split('content:\''))[1].split('\';')[0]

  //提取后面几位数 good_individual_price_FJGfbj84A").html(
  var excellentLastStr = res.substring(res.indexOf(excellentClass + '\").html'), res.length)
  var excellentLastNum = (excellentLastStr.substring(0, excellentLastStr.indexOf('\')'))).split('(\'')[1]

  var goodLastStr = res.substring(res.indexOf(goodClass + '\").html'), res.length)
  var goodLastNum = (goodLastStr.substring(0, goodLastStr.indexOf('\')'))).split('(\'')[1]

  var commonLastStr = res.substring(res.indexOf(commonClass + '\").html'), res.length)
  var commonLastNum = (commonLastStr.substring(0, commonLastStr.indexOf('\')'))).split('(\'')[1]


  var result = {
    img: img,
    minPrice: commonPreNum + commonLastNum,
    middlePrice: goodPreNum + goodLastNum,
    maxPrice: excellentPreNum + excellentLastNum,
    newPrice: condition.curModels.model_price,
    condition: condition,
    error: false
  }
  return result
}

export const evaluteEscf = (obj, _self, condition, callback) => {
  // var url = 'http://www.che168.com/Evaluate/v2/EvaCar.aspx?pgtype=1&pgbid=117&pgsid=2097&pgspid=24355&pgyear=2015&pgmonth=9&pgpid=350000&pgcid=350100&pgmlg=5&type=1&sellMark=uahp10004&isfromoutside=0 '
  var url = _self.$const.ESCFEVAURL + 'pgtype=1&pgbid=' + condition.curSelect.b_id + '&pgsid=' + condition.curChildSelect.id + '&pgspid=' + condition.curModels.id +
    '&pgyear=' + condition.selectedYear + '&pgmonth=' + condition.selectedMonth + '&pgpid=' + condition.selectedProvince.id + '&pgcid=' + condition.selectedCity.id +
    '&pgmlg=' + condition.distance + '&type=1&sellMark=uahp10004&isfromoutside=0'
  url = getBaseUrl + '?url=' + url
  baseGet(url, (res) => {
    // console.log(res.data)
    var data = eval('(' + res.data.data + ')');
    // console.log(data)
    if (data.error === '0') {
      var msg = data.message
      var nextUrl = _self.$const.ESCFBASEURL + '/pinggu/eva_' + msg[0] + '/1.html?bid=' + condition.curSelect.b_id + '&sid=' + condition.curChildSelect.id +
        '&specId=' + condition.curModels.id + '&registerYear=' + condition.selectedYear + '&registerMonth=' + condition.selectedMonth +
        '&pid=' + condition.selectedProvince.id + '&cid=' + condition.selectedCity.id + '&selectCarName=' + escape(condition.curModels.name) +
        '&sellMark=uahp10004&isfromoutside=0&pgmlg=' + condition.distance + "&cdatestr=" + (parseInt(condition.selectedYear) * 100 + parseInt(condition.selectedMonth)) + '&pvareaid=100656'
      // console.log(nextUrl)
      nextUrl = getBaseUrl + '?url=' + nextUrl
      baseGet(nextUrl, (res) => {
        var data = res.data.data
        var index1 = data.indexOf('var minPrice =')
        var index2 = data.indexOf('var isSuccess')
        var str = data.substring(index1, index2)
        var priceArr = str.split(';')
        var minPrice = parseFloat(priceArr[0].split('=')[1])
        var maxPrice = parseFloat(priceArr[1].split('=')[1])

        var newRes = res.data.data
        newRes = newRes.replace(/\<script((.|\n)*?)\<\/script\>/gi, '')
        newRes = newRes.replace(/\<link((.|\n)*?)\/>/gi, '')
        newRes = newRes.replace(/\<head((.|\n)*?)\<\/head\>/gi, '')
        newRes = newRes.replace(/<script.*?>.*?<\/script>/ig, '')
        obj.html(newRes)
        var img = obj.find('.trend-cont-r .trend-r-pic a img')
        var imgUrl = ''
        if (img.length > 0) {
          imgUrl = img.eq (0).attr('src')
        }
        var lastUrl = _self.$const.ESCFBASEURL + '/Handler/Evaluate/EvalResult.ashx?type=1' + '&spid=' + condition.curModels.id + '&cid=' + condition.selectedCity.id +
          '&maxPrice=' + maxPrice + '&minPrice=' + minPrice
        lastUrl = getBaseUrl + '?url=' + lastUrl
        baseGet(lastUrl, (res) => {
          var newData = eval("("+res.data.data+")")
          var resultObj = {
            img: imgUrl,
            minPrice: minPrice,
            middlePrice: _self.$const.toDecimal2((minPrice + maxPrice) / 2),
            maxPrice: maxPrice,
            newPrice: newData.newPrice,
            condition: condition,
            error: false
          }
          // console.log(resultObj)
          callback(resultObj)
        })
      })
    } else { 
      var resultObj = {
        error: true
      }
      callback(resultObj)
      alert("获取二手车之家数据有误");
    }
  })
}

const handlerError = (callback) => {
  var result = {
    error: true
  }
  // console.log(result)
  callback(result)
}